package com.googlecode.jmicroerp.wicket.login;

import com.googlecode.jmicroerp.model.Rol;
import com.googlecode.jmicroerp.model.Utilizator;
import com.googlecode.jmicroerp.repository.GenericRestriction;
import com.googlecode.jmicroerp.security.SpringLoginContext;
import com.googlecode.jmicroerp.service.GenericService;
import com.googlecode.jmicroerp.wicket.SecuredWebSession;
import com.googlecode.jmicroerp.wicket.index.IndexPage;
import com.googlecode.jmicroerp.wicket.vanzare.PosPage;
import java.util.Arrays;
import java.util.Date;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.wicketstuff.security.authentication.LoginException;
import org.wicketstuff.security.hive.authentication.LoginContext;
import org.wicketstuff.security.components.SecureWebPage;

/**
 *
 * @author alex
 */
public class LoginPage extends WebPage {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginPage.class);
    private String username;
    private String password;    
    @SpringBean(name = "genericService")
    private GenericService<Utilizator> genericService;
    
    private Link createNavigationLink(String id, final Class<? extends SecureWebPage> pageClass) {
        Link link = new Link(id) {
            @Override
            public void onClick() {
                setResponsePage(pageClass);
            }
        };
        return link;
    }
    
    public LoginPage() {
        creazaFormaLogin();
    }
    
    private void creazaFormaLogin() {
    
        Link linkPos = createNavigationLink("vanzare_menu", PosPage.class);
        add(linkPos);
        final Form<LoginPage> form = new Form<LoginPage>("form");
        form.setModel(new CompoundPropertyModel<LoginPage>(this));
        form.add(new TextField("username").setRequired(true));
        form.add(new PasswordTextField("password").setRequired(true));
        final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
        form.add(feedbackPanel);
        
        SubmitLink loginButton = new SubmitLink("submit") {

            @Override
            public void onSubmit() {
                LoginContext context = new SpringLoginContext(username, password);
                try {
                    ((SecuredWebSession) getSession()).login(context);
                    GenericRestriction genericRestriction = new GenericRestriction("numeUtilizator", username);
                    Utilizator utilizatorDb = genericService.getSingleResult(Utilizator.class, genericRestriction);
                    for (Rol rol : utilizatorDb.getRoluri()) {
                        if (!"ROLE_USER".equals(rol.getDenumire())) {
                            setResponsePage(IndexPage.class);
                            return;
                        }
                    }
                    setResponsePage(PosPage.class);
                } catch (LoginException e) {
                    if (e.getCause() == null) {
                        error(LoginPage.this.getString("error.dejaAutentificat"));  
                    } else if (e.getCause() instanceof AccountStatusException) {
                        error(LoginPage.this.getString("error.contBlocat"));  
                    } else if (e.getCause() instanceof UsernameNotFoundException) {
                        form.error(LoginPage.this.getString("error.credentialeGresite"));
                    } else if (e.getCause() instanceof BadCredentialsException) {
                        form.error(LoginPage.this.getString("error.credentialeGresite"));
                    } else {
                        long cod = new Date().getTime();
                        LOGGER.error(e.getMessage(), e);
                        form.error("Eroare interna la autentificare (cod: " + cod + ")");
                    }
                } finally {
                    // Don't let the password hanging around
                    password = null;
                }
            }
            
        };
        
        form.add(loginButton);
        form.setDefaultButton(loginButton);

        add(form);
    }
}
